<script setup lang="ts">
import { useI18n } from "vue-i18n";
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import TypeIt from "@/components/ReTypeit";
import { debounce, useGlobal } from "@pureadmin/utils";
import { useNav } from "@/layout/hooks/useNav";
import { useEventListener } from "@vueuse/core";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { $t, transformI18n } from "@/plugins/i18n";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { getTopMenu, initRouter } from "@/router/utils";
import { avatar, bg, illustration } from "./utils/static";
import { ReImageVerify } from "@/components/ReImageVerify";
import { computed, onMounted, reactive, ref, toRaw } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import globalization from "@/assets/svg/globalization.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import Check from "@iconify-icons/ep/check";
import User from "@iconify-icons/ri/user-3-fill";
import Info from "@iconify-icons/ri/information-line";
import { encrypt } from "@/utils/rsaEncrypt";
import Cookies from "js-cookie";
import logoMain from "@/assets/login/logo-main.png";
import { useEpThemeStoreHook } from "@/store/modules/epTheme";
import logoMainWhite from "@/assets/login/logo-main-white.png";
const { $config } = useGlobal();
const themHook = useEpThemeStoreHook();
const getLogoTwo = computed(() => {
  if (themHook.epTheme === "light" || themHook.epTheme === "vppDefault") {
    return logoMain;
  } else {
    return logoMainWhite;
  }
});
defineOptions({
  name: "Login"
});

// const imgCode = ref("");
// const loginDay = ref(7);
const router = useRouter();
const loading = ref(false);
const checked = ref(false);
const disabled = ref(false);
const ruleFormRef = ref<FormInstance>();
const reImageVerify = ref<InstanceType<typeof ReImageVerify> | null>(null);
const currentPage = computed(() => {
  // return useUserStoreHook().currentPage;
  return 0;
});

const { t } = useI18n();
const { initStorage } = useLayout();
initStorage();
const { dataTheme, overallStyle, dataThemeChange } = useDataThemeChange();
dataThemeChange(overallStyle.value);
const { title, getDropdownItemStyle, getDropdownItemClass } = useNav();
const { locale, translationCh, translationEn } = useTranslationLang();

const ruleForm = reactive({
  username: "",
  password: "",
  verifyCode: ""
});

const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      const uuid = reImageVerify.value.codeData.uuid;
      if (checked.value) {
        Cookies.set("uname", ruleForm.username);
        Cookies.set("pwd", ruleForm.password);
        Cookies.set("remberMe", "1");
      } else {
        Cookies.remove("uname");
        Cookies.remove("pwd");
        Cookies.set("remberMe", "0");
      }
      useUserStoreHook()
        .loginByUsername({
          username: ruleForm.username,
          password: encrypt(ruleForm.password),
          code: ruleForm.verifyCode,
          uuid: uuid
        })
        .then(res => {
          if (res) {
            // 获取后端路由
            return initRouter().then(() => {
              disabled.value = true;
              router
                .push(getTopMenu(true).path)
                .then(() => {
                  message("登录成功", { type: "success" });
                })
                .finally(() => (disabled.value = false));
            });
          } else {
            loading.value = false;
            reImageVerify.value.setAuthCodeData();
          }
        })
        .catch(e => {
          if (e && e.response && e.response.data.message) {
            ElMessage({
              message: e.response.data.message,
              type: "error"
            });
          }
          loading.value = false;
          reImageVerify.value.setAuthCodeData();
        })
        .finally(() => {
          loading.value = false;
          // reImageVerify.value.setAuthCodeData()
        });
    } else {
      return fields;
    }
  });
};

const immediateDebounce: any = debounce(
  formRef => onLogin(formRef),
  1000,
  true
);

useEventListener(document, "keypress", ({ code }) => {
  if (code === "Enter" && !disabled.value && !loading.value)
    immediateDebounce(ruleFormRef.value);
});

onMounted(() => {
  const re = Cookies.get("remberMe");
  if (re && re === "1") {
    const uname = Cookies.get("uname");
    const pwd = Cookies.get("pwd");
    ruleForm.username = uname;
    ruleForm.password = pwd;
    checked.value = true;
  } else {
    ruleForm.username = "";
    ruleForm.password = "";
    checked.value = false;
  }
});
</script>

<template>
  <div class="select-none dark:bg-[#182855] bg-white">
    <img :src="bg" class="wave" />
    <div class="flex-c absolute right-5 top-3">
      <!-- 主题 -->
      <el-switch
        v-model="dataTheme"
        inline-prompt
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        @change="dataThemeChange"
      />
      <!-- 国际化 -->
      <el-dropdown trigger="click">
        <globalization
          class="hover:text-primary hover:!bg-[transparent] w-[20px] h-[20px] ml-1.5 cursor-pointer outline-none duration-300"
        />
        <template #dropdown>
          <el-dropdown-menu class="translation">
            <el-dropdown-item
              :style="getDropdownItemStyle(locale, 'zh')"
              :class="['dark:!text-white', getDropdownItemClass(locale, 'zh')]"
              @click="translationCh"
            >
              <IconifyIconOffline
                v-show="locale === 'zh'"
                class="check-zh"
                :icon="Check"
              />
              简体中文
            </el-dropdown-item>
            <el-dropdown-item
              :style="getDropdownItemStyle(locale, 'en')"
              :class="['dark:!text-white', getDropdownItemClass(locale, 'en')]"
              @click="translationEn"
            >
              <span v-show="locale === 'en'" class="check-en">
                <IconifyIconOffline :icon="Check" />
              </span>
              English
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <!--          <avatar class="avatar" />-->
          <div
            class="flex justify-center align-center py-[10px] text-[20px] wenzitiaodong"
          >
            {{ $config.CopyRightData }}
            <!--            L-VPP 能源辅助决策平台-->
            <!--                        <img :src="avatar" alt="vpp" />-->
            <!--            <img :src="getLogoTwo" alt="" />-->
          </div>
          <!--          <Motion>-->
          <!--            <h2 class="outline-none">-->
          <!--              <TypeIt-->
          <!--                :options="{ strings: [title], cursor: false, speed: 100 }"-->
          <!--              />-->
          <!--            </h2>-->
          <!--          </Motion>-->

          <el-form
            v-if="currentPage === 0"
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: transformI18n($t('login.usernameReg')),
                    trigger: 'blur'
                  }
                ]"
                prop="username"
              >
                <el-input
                  v-model="ruleForm.username"
                  clearable
                  :placeholder="t('login.username')"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password">
                <el-input
                  v-model="ruleForm.password"
                  clearable
                  show-password
                  :placeholder="t('login.password')"
                  :prefix-icon="useRenderIcon(Lock)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="200">
              <el-form-item prop="verifyCode">
                <el-input
                  v-model="ruleForm.verifyCode"
                  clearable
                  :placeholder="t('login.verifyCode')"
                  :prefix-icon="useRenderIcon('ri:shield-keyhole-line')"
                >
                  <template v-slot:append>
                    <ReImageVerify ref="reImageVerify" />
                    <!--                    <img :src="imgCode" alt="">-->
                  </template>
                </el-input>
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-form-item>
                <div class="w-full h-[20px] flex justify-between items-center">
                  <el-checkbox v-model="checked">
                    <span class="flex">
                      <!--                      <select-->
                      <!--                        v-model="loginDay"-->
                      <!--                        :style="{-->
                      <!--                          width: loginDay < 10 ? '10px' : '16px',-->
                      <!--                          outline: 'none',-->
                      <!--                          background: 'none',-->
                      <!--                          appearance: 'none'-->
                      <!--                        }"-->
                      <!--                      >-->
                      <!--                        <option value="1">1</option>-->
                      <!--                        <option value="7">7</option>-->
                      <!--                        <option value="30">30</option>-->
                      <!--                      </select>-->
                      {{ t("login.remember") }}
                      <el-tooltip
                        effect="dark"
                        placement="top"
                        :content="t('login.rememberInfo')"
                      >
                        <IconifyIconOffline :icon="Info" class="ml-1" />
                      </el-tooltip>
                    </span>
                  </el-checkbox>
                  <!--                  <el-button-->
                  <!--                    link-->
                  <!--                    type="primary"-->
                  <!--                    @click="useUserStoreHook().SET_CURRENTPAGE(4)"-->
                  <!--                  >-->
                  <!--                    {{ t("login.forget") }}-->
                  <!--                  </el-button>-->
                </div>
                <el-button
                  class="w-full mt-4"
                  size="default"
                  type="primary"
                  :loading="loading"
                  :disabled="disabled"
                  @click="onLogin(ruleFormRef)"
                >
                  {{ t("login.login") }}
                </el-button>
              </el-form-item>
            </Motion>

            <!--            <Motion :delay="300">-->
            <!--              <el-form-item>-->
            <!--                <div class="w-full h-[20px] flex justify-between items-center">-->
            <!--                  <el-button-->
            <!--                    v-for="(item, index) in operates"-->
            <!--                    :key="index"-->
            <!--                    class="w-full mt-4"-->
            <!--                    size="default"-->
            <!--                    @click="useUserStoreHook().SET_CURRENTPAGE(index + 1)"-->
            <!--                  >-->
            <!--                    {{ t(item.title) }}-->
            <!--                  </el-button>-->
            <!--                </div>-->
            <!--              </el-form-item>-->
            <!--            </Motion>-->
          </el-form>

          <!--          <Motion v-if="currentPage === 0" :delay="350">-->
          <!--            <el-form-item>-->
          <!--              <el-divider>-->
          <!--                <p class="text-gray-500 text-xs">{{ t("login.thirdLogin") }}</p>-->
          <!--              </el-divider>-->
          <!--              <div class="w-full flex justify-evenly">-->
          <!--                <span-->
          <!--                  v-for="(item, index) in thirdParty"-->
          <!--                  :key="index"-->
          <!--                  :title="t(item.title)"-->
          <!--                >-->
          <!--                  <IconifyIconOnline-->
          <!--                    :icon="`ri:${item.icon}-fill`"-->
          <!--                    width="20"-->
          <!--                    class="cursor-pointer text-gray-500 hover:text-blue-400"-->
          <!--                  />-->
          <!--                </span>-->
          <!--              </div>-->
          <!--            </el-form-item>-->
          <!--          </Motion>-->
          <!-- 手机号登录 -->
          <!--          <phone v-if="currentPage === 1" />-->
          <!-- 二维码登录 -->
          <!--          <qrCode v-if="currentPage === 2" />-->
          <!-- 注册 -->
          <!--          <regist v-if="currentPage === 3" />-->
          <!-- 忘记密码 -->
          <!--          <update v-if="currentPage === 4" />-->
        </div>
      </div>
    </div>
    <div
      class="w-full flex-c absolute bottom-3 text-sm text-[rgba(0,0,0,0.6)] dark:text-[rgba(220,220,242,0.8)]"
    >
      <!--      Copyright © 2020-present  href="https://github.com/pure-admin"-->
      <a class="hover:text-white" target="_blank"> &nbsp;{{ title }} </a>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

.translation {
  ::v-deep(.el-dropdown-menu__item) {
    padding: 5px 40px;
  }

  .check-zh {
    position: absolute;
    left: 20px;
  }

  .check-en {
    position: absolute;
    left: 20px;
  }
}

@keyframes typing {
  from {
    width: 0;
  } /* 从左到右的动画 */
}

@keyframes caret {
  50% {
    border-color: transparent;
  } /* 闪烁动画 */
}

.wenzitiaodong {
  width: 100%; /* 文本的宽度 */
  overflow: hidden;
  white-space: nowrap;
  //border-right: 0.05em solid;
  animation:
    typing 0.8s steps(60),
    caret 1s steps(1) infinite;
}
</style>
